﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mindscape.LightSpeed;
using OrmSmackdown.LightSpeedORM.Mappings;


namespace OrmSmackdown.LightSpeedORM
{
    public class Crud : ICrud
    {
        private LightSpeedContext<Mappings.OrmSmackdownUnitOfWork> ctx;
        private Mappings.OrmSmackdownUnitOfWork uow;

        public Crud()
        {
            ctx = new LightSpeedContext<OrmSmackdownUnitOfWork>();
            ctx.ConnectionString = LightSpeedContext.Default.ConnectionString;
            ctx.PluralizeTableNames = LightSpeedContext.Default.PluralizeTableNames;
            ctx.IdentityMethod = LightSpeedContext.Default.IdentityMethod;

            uow = ctx.CreateUnitOfWork();
        }

        public int Create(string firstName, string lastName, string email)
        {
            var user1 = new Contact { FirstName = firstName, LastName = lastName, Email = email };

            uow.Add(user1);

            uow.SaveChanges();

            return user1.Id;
        }

        public IPerson Read(int id)
        {
            return uow.People.Where(p => p.Id == id).FirstOrDefault() as IPerson;
        }

        public void Update(int id, string firstName, string lastName, string email)
        {
            var person = uow.People.Where(p => p.Id == id).FirstOrDefault() as IPerson;
            person.FirstName = firstName;
            person.LastName = lastName;
            person.Email = email;

            uow.SaveChanges();
        }

        public void Delete(int id)
        {
            var person = uow.People.Where(p => p.Id == id).FirstOrDefault();

            uow.Remove(person);
            uow.SaveChanges();
        }

        public void Dispose()
        {
            uow.Dispose();
        }
    }
}
